package leetcode.code0210;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.Set;

import leetcode.IDebug;


//执行用时：7 ms, 在所有 Java 提交中击败了28.34%的用户
//
//内存消耗：38.8 MB, 在所有 Java 提交中击败了99.63%的用户
//
//通过测试用例：44 / 44
public class Solution implements IDebug {

	public int[] findOrder(int numCourses, int[][] prerequisites) {
		Map<Integer, Set<Integer>> hash = new HashMap<>();
		int[] pre = new int[numCourses];
		for (int[] p : prerequisites) {
			int ai = p[0], bi = p[1];
			Set<Integer> edge = hash.getOrDefault(bi, new HashSet<>());
			edge.add(ai);
			hash.put(bi, edge);
			pre[ai] += 1;
		}
		Queue<Integer> queue = new LinkedList<>();
		for (int i = 0; i < numCourses; i++) {
			if (pre[i] == 0) {
				queue.add(i);
			}
		}
		int[] ans = new int[numCourses];
		int pans = 0;
		while (!queue.isEmpty()) {
			Integer bi = queue.poll();
			ans[pans++] = bi;
			Set<Integer> edge = hash.get(bi);
			if (edge != null) {
				for (Integer ai : edge) {
					if (--pre[ai] == 0) {
						queue.add(ai);
					}
				}
			}
		}
		return pans == numCourses ? ans : new int[] {};
	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
